<?php
/**
 * Created by PhpStorm.
 * User: shutao
 * Date: 2018/9/13
 * Time: 14:26
 */

namespace wechat\controllers;

use tt\common\components\TtPagination;
use tt\common\help\ModelHelper;
use tt\common\help\RequestHelp;
use tt\common\help\ResponseHelp;
use ttcommon\aop\annotation\ControllerAnnotation;
use ttcommon\base\Arrays;
use ttcommon\base\Data;
use ttcommon\base\Upload;
use ttext\backend\admin\hook\QuickMenuHook;
use wechat\models\WeConfig;
use yii\base\UserException;
use yii\helpers\Inflector;

/**
 * @title [微信]配置
 */
class ConfigController extends BaseWechatController implements ControllerAnnotation
{
    /**
     * @title 配置列表
     */
    public function actionIndex()
    {
        // 快速查看
        if ($api = $this->hasApi()) {
            $params = RequestHelp::requestData();
            // 接口列表
            if ('list' == $api) {
                $query = WeConfig::find()->select(['id', 'title', 'appid', 'debug', 'status', 'type', 'is_default']);
                $pagination = new TtPagination(['totalCount' => $query->count()]);

                $data = [];
                foreach ($query->offset($pagination->offset)->limit($pagination->limit)->asArray()->each() as $item) {
                    $item['debug_text'] = WeConfig::debugText($item['debug']);
                    $item['status_text'] = WeConfig::statusText($item['status']);
                    $item['type_text'] = WeConfig::typeText($item['type']);
                    $item['is_default_text'] = WeConfig::isDefaultText($item['is_default']);
                    $data[] = $item;
                }
                $result = [
                    'total' => $pagination->totalCount,
                    'result' => $data
                ];
                ResponseHelp::send($result);
            } elseif ('changeattrs' == $api) {
                Data::hasSet($params, ['id', 'attr']);
                if (!in_array($params['attr'], ['status', 'debug', 'is_default'])) {
                    throw new UserException('不被允许的属性修改');
                }
                $transaction = \Yii::$app->db->beginTransaction();
                try {
                    $model = $this->findById($params['id']);
                    $model->changeAttrs($params['attr']);
//                    pr($model->toArray());
                    if ($model->update() === false) {
                        throw new \Exception(ModelHelper::errorMessages($model));
                    }
                    $transaction->commit();
                } catch (\Exception $e) {
                    $transaction->rollBack();
                    throw new UserException($e->getMessage());
                }
                $attr = $params['attr'];
                ResponseHelp::send([
                    $attr => $model->$attr,
                    $attr . '_text' => call_user_func([$model, ucfirst(Inflector::camelize($attr)) . 'Text'], $model->$attr)
                ]);

            } elseif ('show' == $api) {
                if ($id = RequestHelp::byKey('id')) {
                    QuickMenuHook::$disabled = true;
                    return $this->render('show', [
                        'model' => $this->findById($id)
                    ]);
                }
            }
            throw new \Exception('参数错误!');
        }
        return $this->render('index');
    }

    private function findById($id)
    {
        if (!$model = WeConfig::findOne($id)) {
            throw new UserException('找不到指定的配置');
        }
        return $model;
    }

    /**
     * @title 添加/编辑配置
     */
    public function actionEdit($id = 0)
    {
        QuickMenuHook::$disabled = true;
        $model = $id ? $this->findById($id) : new WeConfig();
        if (RequestHelp::isPost()) {
            $params = RequestHelp::requestData();
            if ('qrcode' == Data::hasValue($params, 'action')) {
                if (RequestHelp::hasFile()) {
                    // 上传的文件
                    $fileInfo = Upload::fileOneInfo();
                }
            }
            $model->attributes = Arrays::values($params, [
                'type', 'title', 'appid', 'appsecret', 'token', 'encodingaeskey', 'debug', 'domain', 'status', 'is_default'
            ]);
            if ($model->validate() && $model->save()) {
                ResponseHelp::send('成功');
            } else {
                throw new UserException(ModelHelper::errorMessages($model));
            }
        }
        if ($id) {
            $model->status = WeConfig::STATUS_ACTIVE;
        }
        return $this->render('edit', [
            'model' => $model
        ]);
    }

    /**
     * @title 删除配置
     */
    public function actionDelete($id)
    {
        if (RequestHelp::isPost()) {
            $model = $this->findById($id);
            if ($model->delete() === false) {
                throw new \Exception(ModelHelper::errorMessages($model));
            }
            ResponseHelp::send('删除成功');
        } else {
            RequestHelp::throwRequestMethodError();
        }
    }
}